/**
 * @file 025.链表中的两数相加.cc
 * @author snow-tyan (zziywang@163.com)
 * @brief {Life is too short to learn cpp.}
 * @version 0.1
 * @date 2021-12-10
 *
 * @copyright Copyright (c) 2021
 *
 */

#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct ListNode {
    ListNode(int val = 0, ListNode *next = nullptr)
        : val(val), next(next) {}
    int val;
    ListNode *next;
};

class Solution
{
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
    {
        l1 = reverseList(l1);
        l2 = reverseList(l2);
        ListNode *dummy = new ListNode();
        ListNode *head = dummy;
        int jinwei = 0;
        while (l1 || l2 || jinwei) {
            int val = 0;
            if (l1) {
                val += l1->val;
                l1 = l1->next;
            }
            if (l2) {
                val += l2->val;
                l2 = l2->next;
            }
            val += jinwei;
            jinwei = 0;
            if (val > 9) {
                val -= 10;
                jinwei = 1;
            }
            ListNode *node = new ListNode(val);
            head->next = node;
            head = head->next;
        }
        return reverseList(dummy->next);
    }

private:
    ListNode *reverseList(ListNode *head)
    {
        ListNode *cur = head, *pre = nullptr;
        while (cur) {
            ListNode *post = cur->next;
            cur->next = pre;
            pre = cur;
            cur = post;
        }
        return pre;
    }
};
